package com.zhang.service.impl;

import com.zhang.dao.CategoryDao;
import com.zhang.dao.impl.CategoryDaoImpl;
import com.zhang.domain.Category;
import com.zhang.service.CategoryService;
import com.zhang.util.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();
//private Jedis jedis = JedisUtil.getJedis(); 不能放在这里 , 因为Communication.java在实例化时 , 也会实例化 CategoryServiceImpl.java ,而CategoryServiceImpl一旦实例化,就会实例化Jedis , 但有可能redis服务没有启动,所以会导致服务报错

    //首先从redis中获取 , 没有才从数据库中
    @Override
    public List<Category> getAll() {
        Jedis jedis = JedisUtil.getJedis();
        List<Category> categories = new ArrayList<>();

        Set<Tuple> categoryKey = jedis.zrangeWithScores("categoryKey", 0, -1);
        if(categoryKey !=null && categoryKey.size() > 0){
            //缓存中有
            for (Tuple tuple : categoryKey) {
                Category category = new Category();
                category.setCid((int) tuple.getScore());
                category.setCname(tuple.getElement());
                categories.add(category);
            }

        }else{
            //缓存中没有
            //从数据库中获取数据
            categories  = categoryDao.getAll();
            if(categories != null && categories.size() > 0){
                for (Category category : categories) {
                    jedis.zadd("categoryKey",category.getCid(),category.getCname());
                }
            }


        }

        return categories;
    }
}
